<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Configuration
 *
 * @author MinhNguyen
 */

class User {
    //put your code here
    public $id;
    public $avatarid;
    public $username;
    public $firstname;
    public $lastname;
    public $address;
    public $birthday;
    public $email;
    public $password;
    public $role;
    public $overallscore;
    
    public static $instance;
    
    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }


    public function __get($name) {
        return $this->$name;
    }
    
    public function __set($name, $value) {
        $this->$name = $value;
    }   

    /**
     * It's constuctor of User with email
     */
    
    public  function __construct() {
        //allocate your stuff
    }

    /**
     * Print message if email is not found in database
     * or print error message if can not connect database
     */
    public static function withEmail($email) {
        $instance = new self();
        $db = Database::getInstance();
        $query = "SELECT * FROM users WHERE email = '$email' OR username = '$email'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                $instance->id = $rows["id"];
                $instance->avatarid = $rows["avatarid"];
                $instance->username = $rows["username"];
                $instance->firstname = $rows["firstname"];
                $instance->lastname = $rows["lastname"];
                $instance->address = $rows["address"];
                $instance->birthday = $rows["birthday"];
                $instance->email = $rows["email"];
                $instance->password = $rows["password"];
                $instance->role = $rows["role"];
                $instance->overallscore = $rows["overallscore"];
                $instance->name = $instance->firstname.' '.$instance->lastname;
                if ($rows["avatarid"])
                    $instance->avatar = Photo::withId($rows["avatarid"]);
                else {
                    $instance->avatar = new Photo();
                    $instance->avatar->url = "Images/avatar-default.gif";
                }
                return $instance;
            }
            else {
                $controller = new ErrorController(new Error(), new ErrorView(), 
                    "404", "Not found any user with provided email");
                $controller->returnError();
                return NULL;
            }
        }
        else {
            return NULL;
        }
    }
    
    public static function withId($id) {
        $instance = new self();
        $db = Database::getInstance();
        $query = "SELECT * FROM users WHERE id = '$id'";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                $instance->id = $rows["id"];
                $instance->avatarid = $rows["avatarid"];
                $instance->username = $rows["username"];
                $instance->firstname = $rows["firstname"];
                $instance->lastname = $rows["lastname"];
                $instance->address = $rows["address"];
                $instance->birthday = $rows["birthday"];
                $instance->email = $rows["email"];
                $instance->password = $rows["password"];
                $instance->role = $rows["role"];
                $instance->overallscore = $rows["overallscore"];
                $instance->name = $instance->firstname.' '.$instance->lastname;
                if ($rows["avatarid"])
                    $instance->avatar = Photo::withId($rows["avatarid"]);
                else {
                    $instance->avatar = new Photo();
                    $instance->avatar->url = "Images/avatar-default.gif";
                }
                return $instance;
            }
            else {
                return NULL;
            }
        }
        else {
            return NULL;
        }
    }
    
    public static function getUserId($statusid){
        $db = Database::getInstance();
        $query = "SELECT * FROM statuses WHERE id ='$statusid'";
        $result = $db->query($query);
        if($result->returnCode == 200){
            if($result->dataTable->numOfRow == 1){
                $row = $result->dataTable->rows[0];
                return $row["userid"];
            }else{
                return NULL;
            }
        }else{
            return NULL;
        }    
    }
    
    public static function getCurrentUserId() {
        global $curUser;
        return $curUser->id;
    }
    
    public static function Login($email, $password){
        $db = Database::getInstance();
        $query = "SELECT * FROM users WHERE email = '$email' OR username = '$email'";
        $result = $db->query($query);
        if($result->returnCode == 200){
            if($result->dataTable->numOfRow == 1){
                $row = $result->dataTable->rows[0];
                if($password == $row["password"]){
                    $_SESSION["userid"] = $row["id"];
                    global $curUser;
                    $instance = User::withId($row["id"]);
                    $curUser = $instance;
                    return array(
                        "avatarid" => $row["avatarid"],
                        "username" => $row["username"],
                        "firstname" => $row["firstname"],
                        "lastname" => $row["lastname"],
                        "address" => $row["address"],
                        "birthday" => $row["birthday"],
                        "email" => $row["email"],
                        "password" => $row["password"],
                        "role" => $row["role"],
                        "overallscore" => $row["overallscore"]
                    );
                }
            }else{
                return NULL;
            }
        }else{
            return NULL;
        }    
    }
    
    public static function addUser($user){
        $db = Database::getInstance();
        $id = $db->getID("users", "id");
        $avatarid = 0;
        $username = $user['login'];
        $fullName = explode(' ', $user['name']);
        $firstName = $fullName[0];
        $lastName = "";
        for($i = 1; $i < sizeof($fullName); $i++){
            if($i == sizeof($fullName) - 1)
                $lastName .= $fullName[$i];
            else
                $lastName .= $fullName[$i]." ";
        }
        $address = $user['address'];
        $birthday = '0000-00-00';
        $email = $user['email'];
        $password = md5($user['password']);
        $role = 1;
        $overallscore = 0;
        $query = "INSERT INTO users (id, avatarid, username, firstname, lastname, address, 
                birthday, email, password, role, overallscore) VALUES 
                ('$id', '$avatarid', '$username', '$firstName', '$lastName', '$address', '$birthday', 
                '$email', '$password', '$role', '$overallscore')";
        $result = $db->query($query);
        if ($result->returnCode == 200) {
            return true;
        }
    }
    
    public static function deleteUser($userid) {
        if(isset($_SESSION['userid'])) {
            $db = Database::getInstance();
            $user = User::withId($userid);
            $query = "DELETE FROM users WHERE id = '$userid'"; 
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                if($user->avatarid != 0){
                    Photo::deletePhoto($user->avatarid);
                }
                User::deleteAllStatus($userid);
                return "true";
            }
            else {
                return "false";
            }
        }
        else {
            return "false";
        }
    }
    
    public static function updateUser($user) {
        if(isset($_SESSION['userid'])) {
            $db = Database::getInstance();
            $userid = $_SESSION['userid'];
            $username = $user['login'];
            $fullName = explode(' ', $user['name']);
            $firstName = $fullName[0];
            $lastName = substr($user['name'], strlen($firstName) + 1);
            $address = $user['address'];
            $birthday = $user['birthday'];
            $email = $user['email'];
            $query = "UPDATE users SET username='$username', firstname='$firstName', lastname='$lastName', address='$address', birthday='$birthday', email='$email' WHERE id='$userid'"; 
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return "true";
            }
            else {
                return "false";
            }
        }
        else {
            return "false";
        }
    }
    
    public static function updateColumn($column, $value) {
        if(isset($_SESSION['userid'])) {
            $db = Database::getInstance();
            $userid = $_SESSION['userid'];
            if($column != "password"){
                $query = "UPDATE users SET $column='$value' WHERE id='$userid'"; 
            }
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                return "true";
            }
            else {
                return "false";
            }
        }
        else {
            return "false";
        }
    }
    
    public static function changePassword($old_password, $password) {
        if(isset($_SESSION['userid'])) {
            $db = Database::getInstance();
            $userid = $_SESSION['userid'];
            $user = User::withId($_SESSION['userid']);
            if(md5($old_password) == $user->password){
                $new_password = md5($password);
                $query = "UPDATE users SET password='$new_password' WHERE id='$userid'"; 
                $result = $db->query($query);
                if ($result->returnCode == 200) {
                    return "Successful";
                }
                else {
                    return "false";
                }
            }else {
                    return "Old password do not match";
            }
        }
        else {
            return "Please sign in";
        }
    }
    
    public static function getPhotoId($userid){
        $db = Database::getInstance();
        $query = "SELECT id FROM photos WHERE id IN (SELECT photoid FROM photodata WHERE statusid IN (SELECT id FROM statuses WHERE userid = '$userid'))";
        $result = $db->query($query);
        if($result->returnCode == 200){
           if($result->dataTable->numOfRow > 0){
               foreach ($result->dataTable->rows as $row){
                   $id = $row['id'];
                   $res = "$res$id;";
               }
               return $res;
           }else
               return false;
        }else
            return false; 
    }
    
     public static function getUsers($position, $length){
        $db = Database::getInstance();
        $query = "SELECT id FROM users ORDER BY overallscore desc LIMIT $position, $length";
        $result = $db->query($query);
        if($result->returnCode == 200){
           if($result->dataTable->numOfRow > 0){
               foreach ($result->dataTable->rows as $row){
                   $id = $row['id'];
                   $res = "$res$id;";
               }
               return $res;
           }else
               return false;
        }else
            return false;
    }
    
    public static function deleteAllStatus($userid) {
        if(isset($_SESSION['userid'])) {
            $db = Database::getInstance();
            $query = "SELECT * FROM statuses WHERE userid = '$userid'"; 
            $result = $db->query($query);
            if ($result->returnCode == 200) {
                foreach($result->dataTable->rows as $row){
                    Status::deleteStatus($row['id']);
                    $photoid = Photo::getPhotoId($row['id']);
                    Photo::deletePhotoData($photoid);
                }
                return "true";
            }
            else {
                return "false";
            }
        }
        else {
            return "false";
        }
    }
}
?>
